//
//  SalaryHomeController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/24.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class SalaryHomeController: YZDisplayViewController {
    
    var warningView: MGWarningView = { //头部的警告条
        let view = MGWarningView()
        view.isUserInteractionEnabled = true
        return view
    }()
    
    fileprivate var _tableView: UITableView!
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView()
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.tableFooterView = UIView()
            _tableView.separatorStyle = .none
            _tableView.showsVerticalScrollIndicator = false
            _tableView.isScrollEnabled = false
            _tableView.backgroundColor = UIColor.mg_backgroundGray
            
            regClass(_tableView, cell: UITableViewCell.self)
            regClass(_tableView, cell: AccountBalanceCell.self)
            //            regClass(_tableView, cell: ProjectCell.self)
            _tableView.register(UINib.init(nibName: "ProjectNormalCell", bundle: nil), forCellReuseIdentifier: "ProjectNormalCell")
            regClass(_tableView, cell: ProjectNoDataCell.self)
            
            return _tableView
        }
    }
    
    var accountBalance: NSNumber? //账户余额，Section one 数据
    var currentProjectModel: ProjectModel? {//当前页面的项目模型
        willSet {
            for vc in self.childViewControllers {
                if vc is WorkingTotalListController {//触发子ViewController去访问服务器获取数据
                    let viewController = vc as! WorkingTotalListController
                    viewController.currentProjectModel = newValue
                }
                if vc is WorkingMonthListController {
                    let viewController = vc as! WorkingMonthListController
                    viewController.currentProjectModel = newValue
                }
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        WWUser.sharedInstance.ensureCertificationStatus { (status) in
            self.setupWarningContent(status: status)
        }
        
        self.getAccountBalanceData()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.mg_backgroundGray
        self.title = "工资"
        NotificationCenter.default.addObserver(self, selector: #selector(doNotifcationAction), name: NSNotification.Name.init(kNotificationSelectedProjectChanged), object: nil)
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "提现", style: .done, target: self, action: #selector(doRightAction))
     self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 15)], for: .normal)
        self.warningView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(doTapAction)))
        NotificationCenter.default.addObserver(self, selector: #selector(doNotificationAction), name: NSNotification.Name.init(kNotificationWithdrawComplete), object: nil)
        
        self.setupViews()
        self.setupAllViewController()
        
        self.getData()
    }
    
    private func setupViews() {
        self.view.addSubview(warningView)
        self.warningView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(64)
            make.left.right.equalTo(self.view)
            make.height.equalTo(0.1)
        }
        
        
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.top.equalTo(self.warningView.snp.bottom)
            make.left.right.equalTo(self.view)
            make.height.equalTo(195)
        }
        
        self.setUpContentViewFrame { [unowned self](contentView) in
            contentView?.snp.makeConstraints({ (make) in
                make.left.right.equalTo(self.view)
                make.top.equalTo(self.tableView.snp.bottom)
                make.bottom.equalTo(self.view).offset(-49)
            })
        }
    }
    
    private  func setupWarningContent( status:CertificationStatus) {
        switch status {
        case .uncertified:
            /*
            let submitVC = CertificationSubmitController.init(.certificate)
            submitVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(submitVC, animated: true)
        */
            return
        case .beReturn:
            self.warningView.backgroundColor = colorWithRGB(r: 254, g: 237, b: 235)
            self.warningView.setWarningText("您的资料审核未通过，请点此重新提交", textColor: colorWithRGB(r: 255, g: 78, b: 59), completion: {
                self.warningView.snp.remakeConstraints { (make) in
                    make.top.equalTo(self.view).offset(64)
                    make.left.right.equalTo(self.view)
                    make.height.equalTo(self.warningView.contentHeight != nil ? self.warningView.contentHeight! + 20 : 0.1)
                }
            })
        case .certificationInProgress:
            self.warningView.backgroundColor = UIColor(red: 1 , green: 1, blue: 235/255, alpha: 1)
            self.warningView.setWarningText("因您的资料尚在审核中，部分功能无法使用", textColor: colorWithRGB(r: 245, g: 106, b: 0), completion: {
                self.warningView.snp.remakeConstraints { (make) in
                    make.top.equalTo(self.view).offset(64)
                    make.left.right.equalTo(self.view)
                    make.height.equalTo(self.warningView.contentHeight != nil ? self.warningView.contentHeight! + 20 : 0.1)
                }
            })
        default:
            self.warningView.snp.remakeConstraints { (make) in
                make.top.equalTo(self.view).offset(64)
                make.left.right.equalTo(self.view)
                make.height.equalTo(0.1)
            }
        }
        
    }
    
    
    private func setupAllViewController() {
        self.setUpUnderLineEffect { (isUnderLineDelayScroll, underLineH, underLineColor, isUnderLineEqualTitleWidth) in
            underLineColor?.pointee = UIColor.mg_blue
        }
        
        self.setUpTitleEffect { (titleScrollViewColor, norColor, selColor, titleFont, titleHeight, titleWidth) in
            
            norColor?.pointee = colorWith255RGB(153, g: 153, b: 153)
            selColor?.pointee = UIColor.mg_blue
        }
        
        let vc1 = WorkingTotalListController()
        vc1.title = "全部"
        self.addChildViewController(vc1)
        
        let vc2 = WorkingMonthListController()
        vc2.title = "按月查询"
        self.addChildViewController(vc2)
    }
    
    
    func getData () {
        
        self.getAccountBalanceData()
        
        self.getProjectData()
    }
    
    //获取工资，section one的数据
    func getAccountBalanceData() {
        AccountBalanceModel.getAccountBalance { (response) in
            if response.success {
                self.accountBalance = response.value
                self.tableView.reloadSections(IndexSet.init(integer: 0), with: .automatic)
            }
            else {
                
            }
        }
    }
    
    
    
    
    //获取项目， section two的数据
    func getProjectData() {
        ProjectModel.projectList(pageIndex: 1, pageSize: 1){(response) in
            if response.success {
                if let arr = response.value, arr.count > 0 {
                    self.currentProjectModel = arr[0]
                }
                else {
                    self.currentProjectModel = nil
                }
                self.tableView.reloadSections(IndexSet.init(integer: 1), with: .automatic)
            }
            else {
               
                self.currentProjectModel = nil
            }
        }
    }
    
    func doNotificationAction() {
        self.getAccountBalanceData()
    }
    
    func doTapAction() {
        let vc = CertificationReviewController()
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func doNotifcationAction() {
        self.getData()
    }
    
    func doRightAction() {
        let vc = WithdrawController()
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    deinit {
        //        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.init(kNotificationSelectedProjectChanged), object: nil)
        NotificationCenter.default.removeObserver(self)
    }
}

enum SalaryHomeTableViewSection: Int {
    case accountBalanse = 0, project
}
extension SalaryHomeController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return CGFloat([60, 100 + 25][indexPath.section])
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let _section = SalaryHomeTableViewSection(rawValue: indexPath.section)!
        
        switch _section {
        case .accountBalanse://工资余额
            let cell = getCell(tableView, cell: AccountBalanceCell.self, indexPath: indexPath)
            
            cell.accessoryType = .disclosureIndicator
            if self.accountBalance != nil {
                cell.bind(self.accountBalance!)
            }
            return cell
        case .project:
            if self.currentProjectModel != nil {
                let cell = tableView.dequeueReusableCell(withIdentifier: "\(ProjectNormalCell.self)", for: indexPath) as! ProjectNormalCell
                cell.accessoryType = .disclosureIndicator
                cell.bind(self.currentProjectModel!)
                return cell
            }
            else {
                let cell = getCell(tableView, cell: ProjectNoDataCell.self, indexPath: indexPath)
                return cell
            }
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let _section = SalaryHomeTableViewSection(rawValue: indexPath.section)!
        
        switch _section {
        case .accountBalanse:
            let vc = AccountBalanceController()
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        case .project:
            let vc = ProjectListViewController()
            vc.hidesBottomBarWhenPushed = true
            vc.confirmSelection = {(projectModel) in
                self.currentProjectModel = projectModel
                
            tableView.reloadSections(IndexSet.init(integer: indexPath.section), with: .automatic)
            }
        self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0.1
        }
        
        return 10
    }
}

